package com.yiqi.zhiyuan.common.romgim.view;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.util.Log;

import com.luck.picture.lib.entity.LocalMedia;
import com.suozhang.framework.utils.T;
import com.yiqi.zhiyuan.R;
import com.yiqi.zhiyuan.common.utils.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

import io.rong.imkit.RongExtension;
import io.rong.imkit.RongIM;
import io.rong.imkit.plugin.IPluginModule;
import io.rong.imkit.plugin.IPluginRequestPermissionResultCallback;
import io.rong.imkit.plugin.image.PictureSelectorActivity;
import io.rong.imkit.utilities.PermissionCheckUtil;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.ImageMessage;

import static android.app.Activity.RESULT_OK;

public class CameraPlugin implements IPluginModule, IPluginRequestPermissionResultCallback {

    Conversation.ConversationType conversationType;
    String targetId;
    RongExtension extension;
    private List<LocalMedia> selectList;
    private String mCompanyUri;
    private Uri imageUri;
    public static final int TAKE_PHOTO = 1;
    public static final int CROP_PHOTO = 2;
    private File mTmpFile;

    @Override
    public Drawable obtainDrawable(Context context) {
        return context.getResources().getDrawable(R.mipmap.ic_take);
    }

    @Override
    public String obtainTitle(Context context) {
        return "拍照";
    }


    @Override
    public void onClick(Fragment currentFragment, RongExtension extension) {
        this.extension=extension;
        this.conversationType = extension.getConversationType();
        this.targetId = extension.getTargetId();
        String[] permissions = new String[]{"android.permission.READ_EXTERNAL_STORAGE", "android.permission.CAMERA"};
        if (PermissionCheckUtil.checkPermissions(currentFragment.getContext(), permissions)) {
//        File outputImage = new File(Environment.getExternalStorageDirectory(),
//                "tempImage" + ".jpg");
//        try {
//            if (outputImage.exists()) {
//                outputImage.delete();
//            }
//            outputImage.createNewFile();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        imageUri = Uri.fromFile(outputImage);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (intent.resolveActivity(currentFragment.getContext().getPackageManager()) != null) {
                try {
                    mTmpFile = FileUtils.createTmpFile(currentFragment.getContext());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (mTmpFile != null && mTmpFile.exists()) {
                    /*获取当前系统的android版本号*/
                    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
                    Log.e("currentapiVersion","currentapiVersion====>"+currentapiVersion);
                    if (currentapiVersion<24){
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTmpFile));
                        extension.startActivityForPluginResult(intent, TAKE_PHOTO,this);
                    }else {
                        ContentValues contentValues = new ContentValues(1);
                        contentValues.put(MediaStore.Images.Media.DATA, mTmpFile.getAbsolutePath());
                        Uri uri = currentFragment.getContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                        extension.startActivityForPluginResult(intent, TAKE_PHOTO,this);
                    }
                } else {
                    T.showShort("mis_error_image_not_exist");
                }
            } else {
                T.showShort("mis_msg_no_camera");

            }

            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

        } else {
            extension.requestPermissionForPluginResult(permissions, TAKE_PHOTO, this);
        }

    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {

                    ImageMessage imageMessage= ImageMessage.obtain(Uri.fromFile(mTmpFile),Uri.fromFile(mTmpFile));
                    RongIM.getInstance().sendMessage(Message.obtain(targetId, conversationType, imageMessage), "", "", new RongIMClient.SendImageMessageCallback() {
                        @Override
                        public void onAttached(Message message) {

                        }

                        @Override
                        public void onError(Message message, RongIMClient.ErrorCode errorCode) {
//                            T.showShort("发送失败!"+errorCode.getMessage());
                        }

                        @Override
                        public void onSuccess(Message message) {
                        }

                        @Override
                        public void onProgress(Message message, int i) {

                        }
                    });

                }

                break;
            case CROP_PHOTO:

                break;
        }


    }

    public boolean onRequestPermissionResult(Fragment fragment, RongExtension extension, int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (PermissionCheckUtil.checkPermissions(fragment.getContext(), permissions)) {
            Intent intent = new Intent(fragment.getContext(), PictureSelectorActivity.class);
            extension.startActivityForPluginResult(intent, 23, this);
        } else {
            extension.showRequestPermissionFailedAlter(PermissionCheckUtil.getNotGrantedPermissionMsg(fragment.getContext(), permissions, grantResults));
        }

        return true;
    }
}